package com.invoicerecognition.backend.service.impl.account;

import com.invoicerecognition.backend.mapper.UserMapper;
import com.invoicerecognition.backend.model.dto.User;
import com.invoicerecognition.backend.service.account.UpdatePhotoService;
import com.invoicerecognition.backend.service.impl.utils.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Service
public class UpdatePhotoServiceImpl implements UpdatePhotoService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, String> updatePhoto(MultipartFile file) {

        Map<String, String> res = new HashMap<>();

        if (file.isEmpty()) {
            res.put("error_message", "error");
            return res;
        }

        // 获取文件的 MIME 类型
        String mimeType = file.getContentType();
        // 将上传的文件转换为字节数组
        byte[] fileBytes = null;
        try {
            fileBytes = file.getBytes();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 将字节数组转换为Base64编码字符串
        String base64Encoded = Base64.getEncoder().encodeToString(fileBytes);

        // 根据 MIME 类型生成合适的 data:image/ 格式
        String imageUrl = "data:" + mimeType + ";base64," + base64Encoded;

        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

        UserDetailsImpl loginUser = (UserDetailsImpl) authentication.getPrincipal();
        User user = loginUser.getUser();

        user.setPhoto(imageUrl);
        userMapper.updateById(user);
        res.put("error_message", "success");
        res.put("imageUrl", imageUrl);

        return res;
    }
}
